package com.example.pdfandword.controller;

import com.alibaba.fastjson.JSON;
import com.example.pdfandword.controller.zhongrui.EquipInfo;
import com.example.pdfandword.controller.zhongrui.JsonRootBean;
import com.example.pdfandword.excel.ChangeExcelData;
import com.example.pdfandword.util.*;
import com.example.pdfandword.vo.PrintHeader;
import com.example.pdfandword.vo.PrintItem;
import com.example.pdfandword.vo.PrintUtil;
import com.fadada.sdk.client.FddClientBase;
import com.fadada.sdk.client.authForfadada.GetCompanyVerifyUrl;
import com.fadada.sdk.client.authForfadada.model.AgentInfoINO;
import com.fadada.sdk.client.authForfadada.model.BankInfoINO;
import com.fadada.sdk.client.authForfadada.model.CompanyInfoINO;
import com.fadada.sdk.client.authForfadada.model.LegalInfoINO;
import com.fadada.sdk.client.request.ExtsignReq;
import fr.opensagres.xdocreport.utils.StringUtils;
import gnu.io.SerialPort;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.itextpdf.xmp.impl.Base64.decode;

@Slf4j
@Controller
public class OutputController {

    private ExecutorService executor = Executors.newCachedThreadPool();
    /**
     * 导出pdf单子
     */

    @Value(value = "${contract.path}")
    private String uploadpath;
    @Value(value = "${bairrong.LoginApi}")
    private String LoginApi;
    @Value(value = "${bairrong.userNameinput}")
    private String userNameinput;
    @Value(value = "${bairrong.pwdinput}")
    private String pwdinput;
    @Value(value = "${bairrong.apiCodeinput}")
    private String apiCodeinput;
    @Value(value = "${bairrong.strapiName}")
    private String strapiName;
    @Value(value = "${bairrong.strconfId}")
    private String strconfId;
    @Value(value = "${bairrong.verapiName}")
    private String verapiName;
    @Value(value = "${bairrong.verconfId}")
    private String verconfId;
    @Value(value = "${zhongrui.gps}")
    private String zrgps;
    @Value(value = "${oss.bucketName}")
    private String bucketName;
    @Value(value = "${contract.type}")
    private String contractType;

    @Value(value = "${fdd.APP_ID}")
    private String APP_ID;
    @Value(value = "${fdd.APP_SECRET}")
    private String APP_SECRET;
    @Value(value = "${fdd.VERSION}")
    private String VERSION;
    @Value(value = "${fdd.HOST}")
    private String HOST;
    @Value(value = "${fdd.cus_name}")
    private String CUSNAME;
    @Value(value = "${fdd.cus_no}")
    private String CUSNO;
    @Value(value = "${oss.type}")
    private String uploadType;

    @PostMapping("/zrgpsinstall")
    @ResponseBody
    public Result<?> zrgpsinstall(@RequestBody conHead conHead, HttpServletResponse response, HttpServletRequest request) {

        Result<?> result = new Result<>();
        try {

            JsonRootBean jsonRootBean = new JsonRootBean();
            List<EquipInfo> eqlist = new ArrayList<>();
            jsonRootBean.setEquipInfo(eqlist);


            return result.success("");
        } catch (Exception e) {
            return result.error500(e.getMessage());
        }
    }

    @ResponseBody
    @PostMapping("/printProductionProcessCard")
    public Result<?> printProductionProcessCard(@RequestBody PrintHeader printHeader, HttpServletResponse response, HttpServletRequest request) {
        log.info("printProductionProcessCard>>printHeader>{}", JSON.toJSON(printHeader));
        BufferedImage bufferImg = null;

        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
        String url = "D:/opt/gylck1.xls";//本地模板文件路径
        HSSFWorkbook wb = null;
        try {
            wb = new HSSFWorkbook(new FileInputStream(url));
        } catch (IOException e) {
            e.printStackTrace();
            Result.error("创建文件流异常！");
        }
        CellStyle cs = wb.createCellStyle();
        CellStyle cs1 = wb.createCellStyle();
        //CellStyle cs2 = wb.createCellStyle();

        // 创建两种字体
        Font f = wb.createFont();
        Font f1 = wb.createFont();

        // 创建第一种字体样式（用于列名）
        f.setFontHeightInPoints((short) 14);
        f.setColor(IndexedColors.BLACK.getIndex());

        // 创建第一种字体样式（用于列名）
        f1.setFontHeightInPoints((short) 12);
        f1.setColor(IndexedColors.BLACK.getIndex());
        if (!StringUtil.isEmpty(printHeader.getData08()) && "1".equals(printHeader.getData08())) {//紧急订单 红色字体
            f.setColor(IndexedColors.RED.getIndex());
            f1.setColor(IndexedColors.RED.getIndex());
        }
        // 设置第一种单元格的样式（用于列名）
        cs.setFont(f);
        cs.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cs.setBorderRight(HSSFCellStyle.BORDER_THIN);
        cs.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cs.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//        cs.setAlignment(HorizontalAlignment.CENTER);
        cs.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//        cs.setVerticalAlignment(VerticalAlignment.CENTER);
        cs.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        cs1.setFont(f1);
        cs1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cs1.setBorderRight(HSSFCellStyle.BORDER_THIN);
        cs1.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cs1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//        cs1.setAlignment(HorizontalAlignment.CENTER_SELECTION);
        cs1.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);
//        cs1.setVerticalAlignment(VerticalAlignment.CENTER);
        cs1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        cs1.setWrapText(true);

        HSSFSheet sheet = wb.getSheetAt(0);
        try {
            bufferImg = QRcodeUtil.createImage(printHeader.getData01());//工单号
            ImageIO.write(bufferImg, "jpg", byteArrayOut);
        } catch (Exception e) {
            Result.error("生成二维码异常！");
        }
        //画图的顶级管理器，一个sheet只能获取一个（一定要注意这点）
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        //anchor主要用于设置图片的属性
        HSSFClientAnchor anchor = new HSSFClientAnchor(15, 15, 0, 0, (short) 4, 0, (short) 5, 3);
//        anchor.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);
        anchor.setAnchorType(ClientAnchor.DONT_MOVE_AND_RESIZE);
        //插入图片
        patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));

//		sheet.setMargin(HSSFSheet.TopMargin, 0);// 页边距（上）
//		sheet.setMargin(HSSFSheet.BottomMargin, 0);// 页边距（下）
//		sheet.setMargin(HSSFSheet.LeftMargin, 0.2);// 页边距（左）
//		sheet.setMargin(HSSFSheet.RightMargin, 0);// 页边距（右
//		sheet.setColumnWidth(0, 5 * 256);
//		sheet.setColumnWidth(1, 7 * 256);
//		sheet.setColumnWidth(2, 15 * 256);
//		sheet.setColumnWidth(3, 25 * 200);

        int cellsNum = 5;
        int pageSize = 1;
        int page = 0;
        short high = 1400;

        Row rowColumnValue5 = sheet.getRow((short) 4); // 列名
        rowColumnValue5.setRowStyle(cs);
        Cell cellh1 = rowColumnValue5.getCell(0);
        cellh1.setCellValue(printHeader.getData02());//内部件号
        cellh1.setCellStyle(cs);

        Cell cellh2 = rowColumnValue5.getCell(1);
        cellh2.setCellValue(printHeader.getData03());//客户件号
        cellh2.setCellStyle(cs);

        Cell cellh3 = rowColumnValue5.getCell(2);
        cellh3.setCellValue(printHeader.getData04());//PCB半成品件号
        cellh3.setCellStyle(cs);

        Cell cellh4 = rowColumnValue5.getCell(3);
        cellh4.setCellValue(printHeader.getData05());//数量
        cellh4.setCellStyle(cs);

        Cell cellh5 = rowColumnValue5.getCell(4);
        cellh5.setCellValue(printHeader.getData06());//订单号
        cellh5.setCellStyle(cs);

        List<PrintItem> listItem = printHeader.getPrintItem();
        for (PrintItem item : listItem) {
            cellsNum++;

            Row rowColumnValue = sheet.getRow((short) page * pageSize + cellsNum); // 列名
            rowColumnValue.setHeight(high);
            Cell cell1 = rowColumnValue.getCell(0);
            cell1.setCellValue(item.getData02());//序号
            cell1.setCellStyle(cs1);
            Cell cell2 = rowColumnValue.getCell(1);
            cell2.setCellValue(item.getData03());//工序
            cell2.setCellStyle(cs1);
            Cell cell3 = rowColumnValue.getCell(2);
            cell3.setCellValue(item.getData04());//操作员
            cell3.setCellStyle(cs1);
            Cell cell4 = rowColumnValue.getCell(3);
            cell4.setCellValue(item.getData05());//数量
            cell4.setCellStyle(cs1);

            //插入图片
            ByteArrayOutputStream byteArrayOutpic = new ByteArrayOutputStream();
            try {
                try {
                    String qrValue = item.getData01();//二维码
                    bufferImg = QRcodeUtil.createImage(qrValue);
                } catch (Exception e) {
                    // TODO: handle exception
                    Result.error("生成二维码异常！");
                }

                ImageIO.write(bufferImg, "jpg", byteArrayOutpic);

                anchor = new HSSFClientAnchor(15, 15, 0, 0, (short) 4, page * pageSize + cellsNum, (short) 5, page * pageSize + cellsNum + 1);
                patriarch.createPicture(anchor, wb.addPicture(byteArrayOutpic.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
            } catch (IOException e) {
                // TODO: handle exception
                Result.error("写入文件流异常！");
            }
        }
        try {
            // 第七步，将文件存到指定位置并打印
            String filest = DateUtils.date2Str(new SimpleDateFormat("yyyyMMddHHmmss"));
            String savaPath = "D:/opt";
            String fileurl = "gylc" + printHeader.getData07() + "/" + filest + "/" + filest + ".xls";

            File file = new File(savaPath + "/" + "gylc" + printHeader.getData07() + "/" + filest);
            savaPath = savaPath.replace("D:/", "D:/");

            if (!file.exists()) {
                file.mkdirs();// 创建文件根目录
            }
            String outfilePath = savaPath + "/" + fileurl;
            FileOutputStream fileOutputStream = new FileOutputStream(outfilePath);//指定路径与名字和格式
            wb.write(fileOutputStream);//将数据写出去
            fileOutputStream.close();//关闭输出流
            PrintUtil.printFile(outfilePath);
            System.out.println("----Excle文件已生成------");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("IO异常！");
        }
        return Result.ok("打印成功！");
    }

    @PostMapping("/print")
    @ResponseBody
    public Result<?> print(@RequestBody conHead conHead, HttpServletResponse response, HttpServletRequest request) {
        Result<?> result = new Result<>();

        String url = "";
        synchronized (this) {
            String path = uploadpath;
            String conUrl = conHead.getContempPath();//在线模板
            List<TableEntity> listTab = conHead.getTableList();
            String[] strs = conHead.getStrings();
            if (org.springframework.util.StringUtils.isEmpty(conUrl)) {
                conUrl = "";
            }
            String mubantype = "docx";
            if (StringUtil.strPos(conUrl, "xlsx")) {
                mubantype = "xlsx";
            }
            String tmpFile = path + conUrl.substring(conUrl.lastIndexOf("/") + 1);
            try {
                File file = new File(tmpFile);
                if (!file.exists()) {
                    WordUtil.download(conUrl, tmpFile);//首先下载模板
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            ConcurrentHashMap<String, String> data = new ConcurrentHashMap<String, String>();
            for (conmap t : conHead.getConmapList()) {
                try {
                    if (!StringUtils.isEmpty(t.getConValue())) {
                        data.put(t.getConKey(), t.getConValue());
                    }
                } catch (Exception e) {
                }
            }
            ConcurrentHashMap<String, InputStream> pictempMap = new ConcurrentHashMap<>();
            if (!StringUtil.isEmpty(conHead.getConBy1())) {
                try {
                    System.out.println("二维码：" + conHead.getConBy1());
                    if (StringUtil.isNotEmpty(conHead.getQrCodeSize())) {
                        System.out.println("二维码大小：" + conHead.getQrCodeSize());
                        pictempMap.put("pic1", new QRcodeUtil().createImagetoInputStream(conHead.getConBy1(), Integer.parseInt(conHead.getQrCodeSize())));
                    } else {
                        pictempMap.put("pic1", new QRcodeUtil().createImagetoInputStream(conHead.getConBy1()));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            try {
                if ("docx".equals(mubantype)) {
                    url = WordUtil.buildandprint(new File(tmpFile), data, strs, listTab, path, conHead.getOrderNo(), conHead.getConNo(), contractType, uploadType, pictempMap);
                } else {
                    ChangeExcelData changeExcelData = new ChangeExcelData();
                    url = changeExcelData.replaceExcel(tmpFile, path, conHead.getOrderNo(), conHead.getConNo() + ".xlsx", data, contractType, uploadType);
                }
                System.out.println("url:" + url);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result.success(url);
    }

    @PostMapping("/batchPrint")
    @ResponseBody
    public Result<?> batchPrint(@RequestBody List<conHead> conHeadList, HttpServletResponse response, HttpServletRequest request) {
        Result<?> result = new Result<>();

        String url = "";
        for (conHead conHead : conHeadList) {
            synchronized (this) {
                String path = uploadpath;
                String conUrl = conHead.getContempPath();//在线模板
                List<TableEntity> listTab = conHead.getTableList();
                String[] strs = conHead.getStrings();
                if (org.springframework.util.StringUtils.isEmpty(conUrl)) {
                    conUrl = "";
                }
                String mubantype = "docx";
                if (StringUtil.strPos(conUrl, "xlsx")) {
                    mubantype = "xlsx";
                }
                String tmpFile = path + conUrl.substring(conUrl.lastIndexOf("/") + 1);
                try {
                    File file = new File(tmpFile);
                    if (!file.exists()) {
                        WordUtil.download(conUrl, tmpFile);//首先下载模板
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ConcurrentHashMap<String, String> data = new ConcurrentHashMap<String, String>();
                for (conmap t : conHead.getConmapList()) {
                    try {
                        if (!StringUtils.isEmpty(t.getConValue())) {
                            data.put(t.getConKey(), t.getConValue());
                        }
                    } catch (Exception e) {
                    }
                }
                ConcurrentHashMap<String, InputStream> pictempMap = new ConcurrentHashMap<>();
                if (!StringUtil.isEmpty(conHead.getConBy1())) {
                    try {
                        System.out.println("二维码：" + conHead.getConBy1());
                        if (StringUtil.isNotEmpty(conHead.getQrCodeSize())) {
                            System.out.println("二维码大小：" + conHead.getQrCodeSize());
                            pictempMap.put("pic1", new QRcodeUtil().createImagetoInputStream(conHead.getConBy1(), Integer.parseInt(conHead.getQrCodeSize())));
                        } else {
                            pictempMap.put("pic1", new QRcodeUtil().createImagetoInputStream(conHead.getConBy1()));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    if ("docx".equals(mubantype)) {
                        url = WordUtil.buildandprint(new File(tmpFile), data, strs, listTab, path, conHead.getOrderNo(), conHead.getConNo(), contractType, uploadType, pictempMap);
                    } else {
                        ChangeExcelData changeExcelData = new ChangeExcelData();
                        url = changeExcelData.replaceExcel(tmpFile, path, conHead.getOrderNo(), conHead.getConNo() + ".xlsx", data, contractType, uploadType);
                    }
                    System.out.println("url:" + url);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return result.success(url);
    }

    @PostMapping("/exportpdf")
    @ResponseBody
    public Result<?> exportpdf(@RequestBody conHead conHead, HttpServletResponse response, HttpServletRequest request) {
        try {
            Thread.sleep(1000);
        } catch (Exception e) {

        }
        Result<?> result = new Result<>();
        String path = uploadpath;
        String conUrl = conHead.getContempPath();//在线模板
        List<TableEntity> listTab = conHead.getTableList();
        String[] strs = conHead.getStrings();
        if (org.springframework.util.StringUtils.isEmpty(conUrl)) {
            conUrl = "";
        }
        String mubantype = "docx";
        if (StringUtil.strPos(conUrl, "xlsx")) {
            mubantype = "xlsx";
        }
        String tmpFile = path + conUrl.substring(conUrl.length() - 10, conUrl.length());
        try {
            WordUtil.download(conUrl, tmpFile);//首先下载模板
        } catch (Exception e) {
        }
        Map<String, String> data = new HashMap<String, String>();
        for (conmap t : conHead.getConmapList()) {
            try {
                if (!StringUtils.isEmpty(t.getConValue())) {
                    data.put(t.getConKey(), t.getConValue());
                }
            } catch (Exception e) {
            }
        }
        Map<String, InputStream> pictempMap = new HashMap<String, InputStream>();

        if (!StringUtil.isEmpty(conHead.getConBy1())) {
            try {
                pictempMap.put("pic1", new QRcodeUtil().createImagetoInputStream(conHead.getConBy1()));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        try {
            String url = "";
            if ("docx".equals(mubantype)) {
                url = WordUtil.build(new File(tmpFile), data, strs, listTab, path, conHead.getOrderNo(), conHead.getConNo(), contractType, uploadType, pictempMap);
            } else {
                ChangeExcelData changeExcelData = new ChangeExcelData();
                url = changeExcelData.replaceExcel(tmpFile, path, conHead.getOrderNo(), conHead.getConNo() + ".xlsx", data, contractType, uploadType);
            }
            return result.success(url);
        } catch (Exception e) {
            return result.success("");
        }
    }


    @PostMapping("/uploadtofadada")//测试
    @ResponseBody
    @ApiOperation(value = "fadada", notes = "fadada")
    public Result<?> uploadtofadada(@RequestBody conHead conHead, HttpServletResponse response, HttpServletRequest request) {
        try {
            Thread.sleep(3000);
        } catch (Exception e) {
        }
        Result<?> result = new Result<>();
        String conUrl = "https://hcht.oss-cn-heyuan.aliyuncs.com/xmns/%EF%BC%88%E5%85%AC%E5%8F%B8%EF%BC%89%E5%BD%A9%E5%8D%B0%E5%8F%8C%E9%9D%A2%E6%B1%BD%E8%BD%A6%E9%87%91%E8%9E%8D%E6%9C%8D%E5%8A%A1%E5%90%88%E5%90%8C.docx";// conHead.getContoUrl();//WORD合同
        String contract_id = conHead.getConNo();
        String contract_title = conHead.getConBy1();
        String singnkeywords = conHead.getConBy2();
        String transaction_id = conHead.getConBy3();
        FddClientBase base = new FddClientBase(APP_ID, APP_SECRET, VERSION, HOST);
        String res = base.invokeUploadDocs(contract_id, contract_title, null, conUrl, ".docx");
        ExtsignReq req = new ExtsignReq();
        req.setCustomer_id(CUSNO);
        req.setTransaction_id(transaction_id);
        req.setContract_id(contract_id);
        req.setClient_role("1");
        if (StringUtil.isEmpty(singnkeywords)) {
            singnkeywords = "汇成汇通（福建）融资租赁有限公司";
        }
        req.setSign_keyword(singnkeywords);
        req.setDoc_title(contract_title);
        String qsresult = base.invokeExtSignAuto(req);
        String viewpdf_url = com.alibaba.fastjson.JSON.parseObject(qsresult).getString("viewpdf_url");

        return result.success(viewpdf_url);

    }

    @PostMapping("/signfadada")
    @ResponseBody
    @ApiOperation(value = "signfadada", notes = "signfadada")
    public Result<?> singfadada(@RequestBody conHead conHead, HttpServletResponse response, HttpServletRequest request) {
        try {
            Thread.sleep(3000);
        } catch (Exception e) {
        }
        Result<?> result = new Result<>();
        String contract_id = conHead.getConNo();
        String contract_title = conHead.getConBy1();
        String singnkeywords = conHead.getConBy2();
        String transaction_id = conHead.getConBy3();
        String APPIDin = conHead.getConBy4();
        String APP_SECRETin = conHead.getConBy5();
        String VERSIONin = conHead.getConBy6();
        String HOSTin = conHead.getConBy7();
        String CUSNOin = conHead.getConBy8();
        String signposi = conHead.getConBy9();
        String conUrl = conHead.getConBy10();
        FddClientBase base = new FddClientBase(APPIDin, APP_SECRETin, VERSIONin, HOSTin);

        String res = base.invokeUploadDocs(contract_id, contract_title, null, conUrl, "." + contractType);
        ExtsignReq req = new ExtsignReq();
        req.setCustomer_id(CUSNOin);
        req.setTransaction_id(transaction_id);
        req.setContract_id(contract_id);
        req.setClient_role("1");
        req.setPosition_type("0");
//        req.setSignature_positions(signposi);
        req.setSign_keyword(singnkeywords);
        req.setDoc_title(contract_title);
        String qsresult = base.invokeExtSignAuto(req);
        System.out.println(qsresult);
        String download_url = com.alibaba.fastjson.JSON.parseObject(qsresult).getString("download_url");
        return result.success(download_url);

    }

    @PostMapping("/zipfadada")
    @ResponseBody
    @ApiOperation(value = "zipfadada", notes = "zipfadada")
    public Result<?> zipfadada(@RequestBody conHead conHead, HttpServletResponse response, HttpServletRequest request) {
        try {
            Thread.sleep(3000);
        } catch (Exception e) {
        }
        Result<?> result = new Result<>();
        String contract_id = conHead.getConNo();
        String APPIDin = conHead.getConBy4();
        String APP_SECRETin = conHead.getConBy5();
        String VERSIONin = conHead.getConBy6();
        String HOSTin = conHead.getConBy7();
        FddClientBase base = new FddClientBase(APPIDin, APP_SECRETin, VERSIONin, HOSTin);
        String qsresult = base.invokeContractFilling(contract_id);
        String coderes = com.alibaba.fastjson.JSON.parseObject(qsresult).getString("code");
        return result.success(coderes);

    }

    @PostMapping("/regfadada")
    @ResponseBody
    @ApiOperation(value = "regfadada", notes = "regfadada")
    public Result<?> regfadada(@RequestBody conHead conHead, HttpServletResponse response, HttpServletRequest request) {
        try {
            Thread.sleep(3000);
        } catch (Exception e) {
        }
        Result<String> result = new Result<>();
        String contract_id = conHead.getConNo();
        String APPIDin = conHead.getConBy4();
        String APP_SECRETin = conHead.getConBy5();
        String VERSIONin = conHead.getConBy6();
        String HOSTin = conHead.getConBy7();
        FddClientBase base = new FddClientBase(APPIDin, APP_SECRETin, VERSIONin, HOSTin);


        String transaction_id = contract_id;
        String open_id = transaction_id;
        String account_type = "2";
        String resultreg = base.invokeregisterAccount(open_id, account_type);
        System.out.println(resultreg);
        String customer_id = com.alibaba.fastjson.JSON.parseObject(resultreg).getString("data");
        System.out.println(customer_id);
//        result.setResult(customer_id);


        return result.success(customer_id);

    }

    @PostMapping("/getfadada")
    @ResponseBody
    @ApiOperation(value = "getfadada", notes = "regfadada")
    public Result<?> getfadada(@RequestBody conHead conHead, HttpServletResponse response, HttpServletRequest request) {
        try {
            Thread.sleep(3000);
        } catch (Exception e) {
        }
        Result<String> result = new Result<>();
        String customer_id = conHead.getConNo();
        String APPIDin = conHead.getConBy4();
        String APP_SECRETin = conHead.getConBy5();
        String VERSIONin = conHead.getConBy6();
        String HOSTin = conHead.getConBy7();
        GetCompanyVerifyUrl comverify = new GetCompanyVerifyUrl(APPIDin, APP_SECRETin, VERSIONin, HOSTin);
        CompanyInfoINO companyInfo = new CompanyInfoINO();
        BankInfoINO bankInfo = new BankInfoINO();
        LegalInfoINO legalInfo = new LegalInfoINO();
        AgentInfoINO agentInfo = new AgentInfoINO();
        String verifyed_way = "";
        String page_modify = "1";//必填
        String m_verified_way = "0";//实名认证套餐类型
        String result_type = "";
        String cert_flag = "1";
        String option = "";
        String verified_serialno = "";
        String legal_name = "";
        String company_principal_type = "1";//1.法人，2代理人
        String notify_url = "http://www.baidu.com";//必填
        String return_url = "http://www.baidu.com";//可填
        System.out.println(customer_id);

        String resultget = comverify.invokeCompanyVerifyUrl(companyInfo, bankInfo, legalInfo
                , agentInfo, customer_id, verifyed_way, m_verified_way, page_modify,
                company_principal_type, return_url, notify_url, result_type, cert_flag, option, verified_serialno, legal_name);
        System.out.println(resultget);
        String data = com.alibaba.fastjson.JSON.parseObject(resultget).getString("data");
        String url = "";
        if (null != data) {
            url = com.alibaba.fastjson.JSON.parseObject(data).getString("url");
            url = decode(url);//import static com.itextpdf.xmp.impl.Base64.decode;
            System.out.println(url);
        }

        return result.success(url);

    }

    @PostMapping("/uploadfadada")
    @ResponseBody
    @ApiOperation(value = "uploadfadada", notes = "uploadfadada")
    public Result<?> uploadfadada(@RequestBody conHead conHead, HttpServletResponse response, HttpServletRequest request) {
        try {
            Thread.sleep(3000);
        } catch (Exception e) {
        }
        Result<String> result = new Result<>();
        String customer_id = conHead.getConNo();
        String APPIDin = conHead.getConBy4();
        String APP_SECRETin = conHead.getConBy5();
        String VERSIONin = conHead.getConBy6();
        String HOSTin = conHead.getConBy7();
        String imgUrl = conHead.getConBy8();
        FddClientBase base = new FddClientBase(APPIDin, APP_SECRETin, VERSIONin, HOSTin);
        String resultqz = base.invokeaddSignature(customer_id, null, imgUrl);
        return result.success(resultqz);

    }

    /***
     * 大数据符号查询
     */
    @PostMapping("/bigdataquery")
    @ResponseBody
    public Result<?> fuhaoquery(@RequestBody conHead conHead,
                                HttpServletResponse response, HttpServletRequest request) {
        List<bigDataRes> resbig = new ArrayList<>();

        Result<?> result = new Result<>();
        String name = conHead.getConBy1();
        String id_number = conHead.getConBy2();
        String mobile = conHead.getConBy3();
        String card = conHead.getConBy4();
        String fktype = conHead.getConBy99();
        System.out.println("fktype==" + fktype);
        if (StringUtil.strPos(fktype, "mishi")) {
            Map map = new HashMap();
            String fytUrl = "type=CR&products=N0132&name=" + name + "&id_number=" + id_number;
            String res = null;
            try {
                res = HttpUtil.post("https://dataapi.mishishuju.com/v1.1.1/data-orders/query", fytUrl);
                System.out.println("法院通 ==== " + res);
                JSONObject obj = JSONObject.fromObject(res);
                if (obj.getInt("status") == 0) {
                    String order_id = obj.getJSONObject("data").getString("order_id");
                    fytUrl = "order_id=" + order_id;
                    res = HttpUtil.post("https://dataapi.mishishuju.com/v1.1.1/data-orders/get-result", fytUrl);
                    JSONObject json = JSONObject.fromObject(res);
                    bigDataRes big1 = new bigDataRes();
                    big1.setBdName("法院通");
                    big1.setBdvalue(json.getJSONObject("data").getString("view_url"));
                    resbig.add(big1);
//                map.put("fyt",json.getJSONObject("data").getString("view_url"));//测试
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            //多贷客
            String ddkUrl = "type=CR&products=N0125&name=" + name + "&id_number=" + id_number;
            try {
                res = HttpUtil.post("https://dataapi.mishishuju.com/v1.1.1/data-orders/query", ddkUrl);
                System.out.println("多贷客 ===== " + res);
                JSONObject obj = JSONObject.fromObject(res);
                if (obj.getInt("status") == 0) {
                    String order_id = obj.getJSONObject("data").getString("order_id");
                    ddkUrl = "order_id=" + order_id;
                    res = HttpUtil.post("https://dataapi.mishishuju.com/v1.1.1/data-orders/get-result", ddkUrl);
                    JSONObject json = JSONObject.fromObject(res);
                    bigDataRes big1 = new bigDataRes();
                    big1.setBdName("多贷客");
                    big1.setBdvalue(json.getJSONObject("data").getString("view_url"));
                    resbig.add(big1);
//                map.put("ddk",json.getJSONObject("data").getString("view_url"));//测试
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            //个人风险信息
            String grfxUrl = "type=CR&products=N0173&name=" + name + "&id_number=" + id_number;
            try {
                res = HttpUtil.post("https://dataapi.mishishuju.com/v1.1.1/data-orders/query", grfxUrl);
                System.out.println("个人风险信息 ==== " + res);
                JSONObject obj = JSONObject.fromObject(res);
                if (obj.getInt("status") == 0) {
                    String order_id = obj.getJSONObject("data").getString("order_id");
                    grfxUrl = "order_id=" + order_id;
                    res = HttpUtil.post("https://dataapi.mishishuju.com/v1.1.1/data-orders/get-result", grfxUrl);
                    JSONObject json = JSONObject.fromObject(res);
                    bigDataRes big1 = new bigDataRes();
                    big1.setBdName("个人风险信息");
                    big1.setBdvalue(json.getJSONObject("data").getString("view_url"));
                    resbig.add(big1);
//                map.put("grfx",json.getJSONObject("data").getString("view_url"));//测试
                }
            } catch (IOException e) {
                e.printStackTrace();
            }


            //实名验证信息
            String smyzUrl = "type=CR&products=N0154&name=" + name + "&id_number=" + id_number;
            try {
                res = HttpUtil.post("https://dataapi.mishishuju.com/v1.2/data-orders/query", smyzUrl);
                JSONObject obj = JSONObject.fromObject(res);
                if (obj.getInt("status") == 0) {
                    bigDataRes big1 = new bigDataRes();
                    big1.setBdName("实名验证信息");
                    big1.setBdvalue(obj.getJSONObject("data").getString("view_url"));
                    resbig.add(big1);
//                map.put("smyz",obj.getJSONObject("data").getString("view_url"));//测试
                    System.out.println("实名验证=====" + map.get("smyz"));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }


            //手机在网时长信息
            String sjscUrl = "type=CR&products=N0193&name=" + name + "&id_number=" + id_number + "&mobile=" + mobile;
            try {
                res = HttpUtil.post("https://dataapi.mishishuju.com/v1.2/data-orders/query?products=N0195", sjscUrl);
                JSONObject obj = JSONObject.fromObject(res);
                if (obj.getInt("status") == 0) {
                    bigDataRes big1 = new bigDataRes();
                    big1.setBdName("手机在网时长信息");
                    big1.setBdvalue(obj.getJSONObject("data").getString("view_url"));
                    resbig.add(big1);
//                map.put("sjsc",obj.getJSONObject("data").getString("view_url"));//测试
                    System.out.println("手机在网时长======" + map.get("sjsc"));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            //手机在网状态信息
            String sjztUrl = "type=CR&products=N0194&name=" + name + "&id_number=" + id_number + "&mobile=" + mobile;
            try {
                res = HttpUtil.post("https://dataapi.mishishuju.com/v1.2/data-orders/query?products=N0195", sjztUrl);
                JSONObject obj = JSONObject.fromObject(res);
                if (obj.getInt("status") == 0) {
                    bigDataRes big1 = new bigDataRes();
                    big1.setBdName("手机在网状态信息");
                    big1.setBdvalue(obj.getJSONObject("data").getString("view_url"));
                    resbig.add(big1);
//                map.put("sjzt",obj.getJSONObject("data").getString("view_url"));//测试
                    System.out.println("手机在网状态=====" + map.get("sjzt"));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            //欺诈风险
            String qzfxUrl = "type=CR&products=N0245&name=" + name + "&id_number=" + id_number + "&mobile=" + mobile;
            try {
                res = HttpUtil.post("https://dataapi.mishishuju.com/v1.2/data-orders/query", qzfxUrl);
                System.out.println("欺诈风险=====" + res);
                JSONObject obj = JSONObject.fromObject(res);
                if (obj.getInt("status") == 0) {
                    bigDataRes big1 = new bigDataRes();
                    big1.setBdName("欺诈风险评估");
                    big1.setBdvalue(obj.getJSONObject("data").getString("view_url"));
                    resbig.add(big1);
                    map.put("qzfx", obj.getJSONObject("data").getString("view_url"));//测试
                    System.out.println("欺诈风险=====" + map.get("qzfx"));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            //手机三要素验证
            String sjsysUrl = "name=" + name + "&id_number=" + id_number + "&mobile=" + mobile;
            try {
                res = HttpUtil.post("https://dataapi.mishishuju.com/v1.2/data-orders/query?products=N0195", sjsysUrl);
                JSONObject obj = JSONObject.fromObject(res);
                if (obj.getInt("status") == 0) {
                    bigDataRes big1 = new bigDataRes();
                    big1.setBdName("手机三要素");
                    big1.setBdvalue(obj.getJSONObject("data").getString("view_url"));
                    resbig.add(big1);
//                map.put("sjsys",obj.getJSONObject("data").getString("view_url"));//测试
                    System.out.println("手机三要素=====" + map.get("sjsys"));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            //银行四要素验证
            String yhsysUrl = "type=CR&products=N0236&name=" + name + "&id_number=" + id_number + "&mobile=" + mobile + "&card=" + card;
            try {
                res = HttpUtil.post("https://dataapi.mishishuju.com/v1.1.1/data-orders/query", yhsysUrl);
                System.out.println(res);
                JSONObject obj = JSONObject.fromObject(res);
                if (obj.getInt("status") == 0) {
                    String order_id = obj.getJSONObject("data").getString("order_id");
                    yhsysUrl = "order_id=" + order_id;
                    res = HttpUtil.post("https://dataapi.mishishuju.com/v1.1.1/data-orders/get-result", yhsysUrl);
                    JSONObject json = JSONObject.fromObject(res);
                    bigDataRes big1 = new bigDataRes();
                    big1.setBdName("银行四要素");
                    big1.setBdvalue(json.getJSONObject("data").getString("view_url"));
                    resbig.add(big1);
//                map.put("yhsys",json.getJSONObject("data").getString("view_url"));//测试
                    System.out.println("银行四要素=====" + map.get("yhsys"));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (StringUtil.strPos(fktype, "fuhao")) {
            String resfh = "";
            try {
                resfh = fhlv.fhlvquery(name, id_number, mobile);
                System.out.println("res==============" + resfh);
                if (StringUtils.isNotEmpty(resfh)) {
                    JSONObject json = JSONObject.fromObject(resfh);
                    if ("200".equals(json.get("code").toString())) {
                        String body = json.get("body").toString();
                        JSONObject jsonbody = JSONObject.fromObject(body);
                        String id = "";
                        id = jsonbody.get("id").toString();
                        if (StringUtils.isNotEmpty(id)) {
                            String pdf = fhlv.fhlvpdf(id);
                            JSONObject jsonpdf = JSONObject.fromObject(pdf);
                            if ("200".equals(jsonpdf.get("code").toString())) {
                                String pdfbody = jsonpdf.get("body").toString();
                                JSONObject jsonbodypdf = JSONObject.fromObject(pdfbody);
                                String base64pdf = jsonbodypdf.get("fileStr").toString();
                                String pdfpath = uploadpath;
                                String fileurlpdf = uploadpath + id + ".pdf";
                                this.base64StringToPdf(base64pdf, fileurlpdf);
                                File file = new File(fileurlpdf);
                                String respdf = OssBootUtil.uploadlocalfile(file, "fuquery", bucketName);
                                if (StringUtils.isNotEmpty(respdf)) {
                                    bigDataRes bg = new bigDataRes();
                                    bg.setBdName("符号大数据");
                                    bg.setBdvalue(respdf);
                                    resbig.add(bg);
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
            }
        }
        if (StringUtil.strPos(fktype, "bairongstr")) {
            String resstrpdf = "";
            try {
                String resultstr = StrategyApi.getstrategyresult(id_number,
                        name, card, mobile,
                        userNameinput, pwdinput, apiCodeinput,
                        strconfId, strapiName, LoginApi
                );
                if (StringUtils.isNotEmpty(resultstr)) {
                    JSONObject json = JSONObject.fromObject(resultstr);
                    try {
                        try {
                            String filepath = StrategyApi.getpdfbg(json.get("swift_number").toString(), userNameinput, pwdinput, apiCodeinput);
                            File file = new File(filepath);
                            resstrpdf = OssBootUtil.uploadlocalfile(file, "bairongstr", bucketName);
                            bigDataRes bg = new bigDataRes();
                            bg.setBdName("百融贷前");
                            bg.setBdvalue(resstrpdf);
                            resbig.add(bg);
                        } catch (Exception e) {
                        }
                    } catch (Exception e) {
                    }
                }
            } catch (Exception e) {
//                e.printStackTrace();
            }
        }
        if (StringUtil.strPos(fktype, "bairongver")) {
            String resverpdf = "";
            try {
                String resultstr = StrategyApi.getstrategyresult(id_number,
                        name, card, mobile,
                        userNameinput, pwdinput, apiCodeinput,
                        verconfId, verapiName, LoginApi
                );
                if (StringUtils.isNotEmpty(resultstr)) {
                    JSONObject json = JSONObject.fromObject(resultstr);
                    try {
                        try {
                            String filepath = StrategyApi.getpdfbg(json.get("swift_number").toString(), userNameinput, pwdinput, apiCodeinput);
                            File file = new File(filepath);
                            resverpdf = OssBootUtil.uploadlocalfile(file, "bairongver", bucketName);
                            bigDataRes bg = new bigDataRes();
                            bg.setBdName("百融验证");
                            bg.setBdvalue(resverpdf);
                            resbig.add(bg);
                        } catch (Exception e) {
                        }
                    } catch (Exception e) {
                    }
                }
            } catch (Exception e) {
//                e.printStackTrace();
            }
        }
        return Result.ok(resbig);
    }

    /***
     * 大数据符号律动下载
     */
    @RequestMapping("/fuhaodownload")
    @ResponseBody
    public Result<?> fuhaodownload(@RequestParam(value = "orderNo", required = false) String orderNo,
                                   HttpServletResponse response, HttpServletRequest request) {
        Result<?> result = new Result<>();
        String res = "";
        try {
            String pdf = fhlv.fhlvpdf(orderNo);
            JSONObject jsonpdf = JSONObject.fromObject(pdf);
            if ("200".equals(jsonpdf.get("code").toString())) {
                String pdfbody = jsonpdf.get("body").toString();
                JSONObject jsonbodypdf = JSONObject.fromObject(pdfbody);
                String base64pdf = jsonbodypdf.get("fileStr").toString();
                String pdfpath = uploadpath;
                String fileurlpdf = uploadpath + orderNo + ".pdf";
                this.base64StringToPdf(base64pdf, fileurlpdf);
                File file = new File(fileurlpdf);
                res = OssBootUtil.uploadlocalfile(file, "fuquery", bucketName);
            }
            return result.success(res);
        } catch (Exception e) {
            return result.error500(e.getMessage());
        }
    }

    /***
     * 发送串口信号
     */
    @RequestMapping("/sendSerialData")
    @ResponseBody
    public Result<?> sendSerialData(@RequestBody conHead conHead,
                                    HttpServletResponse response, HttpServletRequest request) {
        String serialdata = conHead.getConBy1();
        String serialno = conHead.getConBy2();
        Result<?> result = new Result<>();
        String res = "";
        SerialPort port = null;
        if (StringUtils.isEmpty(serialdata)) {
            serialdata = "31";
            serialno = "COM8";
        }
        try {
            System.out.println("开始发送信号,信号" + serialdata + "；端口" + serialno);
//            SerialTool.findPort();
            port = SerialTool.openPort(serialno, 9600);
            SerialTool.sendToPort(port, SerialTool.hexToByteArray2(serialdata));
            return result.success(res);
        } catch (Exception e) {
            System.out.println("发送错误,原因" + e.getMessage());
            return result.error500(e.getMessage());
        } finally {
            SerialTool.closePort(port);
        }
    }

    /**
     * @param base64Content
     * @param filePath      base64字符串转pdf
     */
    public void base64StringToPdf(String base64Content, String filePath) {
        BASE64Decoder decoder = new BASE64Decoder();
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            byte[] bytes = decoder.decodeBuffer(base64Content);// base64编码内容转换为字节数组
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
            bis = new BufferedInputStream(byteInputStream);
            File file = new File(filePath);
            File path = file.getParentFile();
            if (!path.exists()) {
                path.mkdirs();
            }
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            byte[] buffer = new byte[1024];
            int length = bis.read(buffer);
            while (length != -1) {
                bos.write(buffer, 0, length);
                length = bis.read(buffer);
            }
            bos.flush();
        } catch (Exception e) {
//            e.printStackTrace();
        } finally {
            try {
                bos.close();
                fos.close();
                bis.close();
            } catch (IOException e) {
//                e.printStackTrace();
            }

        }
    }
}
